package com.pets.web.controller.api;


import com.pets.common.annotation.RateLimiter;
import com.pets.common.core.controller.BaseController;
import com.pets.common.core.domain.AjaxResult;
import com.pets.common.core.page.TableDataInfo;
import com.pets.common.enums.LimitType;
import com.pets.common.utils.OssUtils;
import com.pets.common.utils.StringUtils;
import com.pets.web.entity.PetsComment;
import com.pets.web.service.IPetsCommentService;
import com.pets.web.vo.ApiPetsCommentAddRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 商品评论表 前端控制器
 * </p>
 *
 * @author zhurenwang
 * @since 2024-05-26
 */
@Api(tags = "商品评论相关接口")
@RestController
@RequestMapping("/api/comment")
public class ApiPetsCommentController extends BaseController {

    @Autowired
    private IPetsCommentService petsCommentService;
    @Autowired
    private OssUtils ossUtils;

    @ApiOperation("添加评论")
    @RateLimiter(time = 5, count = 5, limitType = LimitType.IP)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ApiPetsCommentAddRequest request){
        try {
            return success(petsCommentService.add(request));
        }catch (Exception e){
            if (Objects.nonNull(request.getPics())){
                request.getPics().forEach(pic -> ossUtils.deleteFile(pic));
            }
            throw e;
        }
    }

    @ApiOperation("获取评论列表")
    @GetMapping("/list/{goodsId}")
    public TableDataInfo<PetsComment> getCommentList(@ApiParam("商品id") @NotNull @PathVariable Integer goodsId) {
        startPage();
        List<PetsComment> list = petsCommentService.getCommentList(goodsId);
        return getDataTable(list);
    }

}
